package com.mmall.common;

import com.mmall.util.PropertiesUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {
	private static JedisPool pool;
	private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20"));
	private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "20"));
	private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle", "20"));

	private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow", "true"));
	private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return", "true"));

	private static String redisIp = PropertiesUtil.getProperty("redis.ip");
	private static Integer redisPort = Integer.parseInt(PropertiesUtil.getProperty("redis.port"));

	private static void initPool() {// 这是一个静态方法，后面加个静态块调用它，只执行一次，为防止外部有代码调用它，用private
		JedisPoolConfig config = new JedisPoolConfig();

		config.setMaxTotal(maxTotal);
		config.setMaxIdle(maxIdle);
		config.setMinIdle(minIdle);

		config.setTestOnBorrow(testOnBorrow);
		config.setTestOnReturn(testOnReturn);

		config.setBlockWhenExhausted(true);// 连接耗尽的时候，是否阻塞，false会抛出异常，true阻塞直到超时。默认为true。

		pool = new JedisPool(config, redisIp, redisPort, 1000 * 2);

	}

	static {// 这个类在加载到jvm的时候就初始化这个连接池。
		initPool();
	}

	public static Jedis getJedis() {
		return pool.getResource();
	}

	// 下面了两个方法把jedis放回连接池：
	public static void returnBrokenResource(Jedis jedis) {
		pool.returnBrokenResource(jedis);// 源码里已经判空了，所以这里不用判空了。
	}

	public static void returnResource(Jedis jedis) {
		pool.returnResource(jedis);
	}

	public static void main(String[] args) {
		Jedis jedis = pool.getResource();
		jedis.set("aa", "11");
        returnResource(jedis);
		pool.destroy();
		System.out.println("ok");
	}

}
